package cn.goktech.util;

import cn.goktech.properties.DBConnectionProperties;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @ClassName DBConnUtil
 * @Discription 数据库连接工具类
 * @Author Carter
 * @Date 2021/4/18 11:12
 * @Version 1.0
 **/
public class DBConnUtil {

    /**
     * 获取数据库连接
     * @param dbConnectionProperties 数据库连接配置信息
     * @param dbName 制定获取数据库名
     * @return 数据库连接
     */
    public static Connection getConnection(DBConnectionProperties dbConnectionProperties,String dbName){
        String youDBName = "";
        if(dbName==null||"".equals(dbName.trim())){
            youDBName = "mysql";
        }else{
            youDBName = dbName;
        }
        Connection conn = null;
        try {
            Class.forName(dbConnectionProperties.getDriverClass());//加载驱动
            conn = DriverManager.getConnection(dbConnectionProperties.getUrl().replaceAll("yourname",youDBName),
                    dbConnectionProperties.getUserName(),
                    dbConnectionProperties.getPassWorld());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }



    /**
     * 关闭数据库连接
     * @param conn 需要关闭的数据库连接
     */
    public static void closeConn(Connection conn){
        try {
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
